package com.example.kotapp.ui.main.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.coszero.common.config.RequestCode;
import com.coszero.common.utils.glide.ImageLoad;
import com.coszero.common.utils.matisse.SelectImageUtils;
import com.coszero.common.utils.permission.PermissionHelper;
import com.coszero.common.utils.xpopup.XPopupUtils;
import com.coszero.ui.dialog.ToastUtils;
import com.coszero.utils.media.SoundPoolUtils;
import com.coszero.utils.utils.LogX;
import com.coszero.utils.utils.StringUtils;
import com.example.kotapp.common.apiadapter.NotificationChannelUtils;
import com.example.kotapp.common.base.BaseMyActivity;
import com.example.kotapp.common.dialog.ChoosePictureDialog;
import com.example.kotapp.common.event.LoginEvent;
import com.example.kotapp.common.testdata.TestUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Arrays;
import java.util.List;


/**
 * Desc： 主页
 *
 * @author xmqian
 * Email:xmqian93@163.com
 * Date: 2025/4/16
 */
public class ListMainActivity extends BaseMyActivity {
    /**
     * 退出间隔时间
     */
    private static final long DELAY_TIME = 1500;
    private long lastPressBackKeyTime = 0;
    private TestUtils testUtils;
    SmartRefreshLayout smartRefreshLayout;
    ImageView mIvImage;
    private String takePhotoPath;
    private PermissionHelper permissionHelper;
    /**
     * 相机照片路径
     */
    private String cameraPath;
    private SoundPoolUtils poolUtils;
    private ActivityTestRunBinding binding;

    @Override
    protected View getLayoutView() {
        setDisplayFullScreen();
        binding = ActivityTestRunBinding.inflate(getLayoutInflater());
        setStatusBarPadding(binding.lvList);
        return binding.getRoot();
    }

    // <editor-fold desc="生命周期" defaultstate="collapsed">
    @Override
    public void initView() {
        smartRefreshLayout = binding.refreshLayout;
        mIvImage = binding.ivImage;


        smartRefreshLayout.setOnRefreshListener(refreshlayout -> {
            refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshlayout -> {
            refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
        });
        testUtils = TestUtils.newInstance(this);
        String[] stringArray = getResources().getStringArray(R.array.item_name);
        final List<String> items = Arrays.asList(stringArray);
        ListView listView = findViewById(R.id.lv_list);
        listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, items) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = new TextView(getContext());
                textView.setText(items.get(position));
                textView.setTextSize(16);
                textView.setBackgroundColor(0x99ffffff);
                textView.setPadding(0, 30, 0, 30);
                textView.setGravity(Gravity.CENTER);
                textView.setTypeface(Typeface.DEFAULT_BOLD);
                return textView;
            }
        });
        listView.setOnItemClickListener((parent, view, position, id) -> use(position));
        //初始化渠道通知，8.0+
        NotificationChannelUtils.newInstance(this).init();
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        permissionHelper.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TestUtils.REQUEST_TAKE_PHOTO_CODE:
                    //相机
                    if (!StringUtils.isEmpty(cameraPath)) {
                        File file = new File(cameraPath);
                        LogX.i("### 拍摄照片后的路径：" + cameraPath + "\n 文件大小：" + file.length());
                        ImageLoad.loadImage(this, cameraPath, mIvImage);
                    }
                    break;
                case SelectImageUtils.REQUEST_CODE_CHOOSE:
                    List<String> imagePaths = SelectImageUtils.getImagePaths(data);
                    String s = imagePaths.get(0);
                    ImageLoad.loadImage(this, s, mIvImage);
                    break;
                case SelectImageUtils.REQUEST_CODE_CHOOSE_PHOTO_SHOOT:
                    String takePhotoFile = SelectImageUtils.getTakePhotoFile(takePhotoPath);
                    ImageLoad.loadImage(this, takePhotoFile, mIvImage);
                    break;
            }
        }
    }

    //</editor-fold>
    private void use(int pos) {
        switch (pos) {
            case 0://申请权限
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.setTitle("温馨提示")
                        .setMessage("申请相机，读写，定位权限")
                        .setPositiveButton("确定开启", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                PermissionHelper.requestEasy(TestMainActivity.this, new PermissionHelper.CallBackFail() {
                                    @Override
                                    public void requestFail() {
                                        ToastUtils.showMsg("权限申请失败");
                                    }

                                    @Override
                                    public void requestSuccess() {
                                        ToastUtils.showLongMsg("权限申请成功");
                                    }
                                });
                            }
                        }).show();
                break;
            case 1://打开相机
                permissionHelper = new PermissionHelper();
                permissionHelper.requestActivity(mActivity, Manifest.permission.CAMERA, RequestCode.REQUEST_PERMISSION_CODE, () -> cameraPath = testUtils.takePhoto());
                break;
            case 2://渠道通知
                NotificationChannelUtils.newInstance(this).sendMessage();
                LogX.d("### 通知渠道 ---使用自定义jar");
                break;
            case 3://登录注册
                LoginActivity.startTask(this);
                break;
            case 4://通用网页
                startActivity(MyWebViewActivity.getIntent(this, "通用网页", "https://www.baidu.com"));
                break;
            case 5://头像选择弹窗
                XPopupUtils xPopupUtils = new XPopupUtils(this);
                xPopupUtils.init(new ChoosePictureDialog(this, new ChoosePictureDialog.ChoosePictureCallBack() {
                    @Override
                    public void selectGallery() {
                        SelectImageUtils.selectSingleImage(TestMainActivity.this);
                    }

                    @Override
                    public void selectCapture() {
                        SelectImageUtils.takePhoto(TestMainActivity.this, path -> {
                            takePhotoPath = path;
                        });
                    }
                })).show();
                break;
            case 6://普通主页
                ListMainActivity.startActivity(mActivity);
                break;
            case 7://下方菜单的主页
                MainBottomTabActivity.startTask(mActivity);
                break;
            case 8://媒体音频测试
                //播放短促音频
                if (poolUtils == null) {
                    poolUtils = new SoundPoolUtils(this);
                }
                poolUtils.playSoundWithRedId(R.raw.barcodebeep);
                //播放长音频
//                MediaPlayerUtils.playAdudio(this, R.raw.tip_network_and_request_faile_please_try_again);
                LogX.i("播放音频文件");
                break;
            case 9://页面预览
                PagePreviewActivity.startActivity(mActivity);
                break;
            default:
                break;
        }
    }

    private void showWaringDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("警告！")
                .setMessage("请前往设置->应用->" + getString(R.string.app_name) + "->权限中打开相关权限，否则功能无法正常运行！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 一般情况下如果用户不授权的话，功能是无法运行的，做退出处理
//                        finish();
                    }
                }).show();
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
            super.onBackPressed();
        } else {
            lastPressBackKeyTime = System.currentTimeMillis();
            ToastUtils.showLongMsg(getResources().getString(R.string.toast_press_again_exit_app));
        }
    }

    /*@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
                return super.onKeyDown(keyCode, event);
            } else {
                lastPressBackKeyTime = System.currentTimeMillis();
                ToastUtils.showLongMsg(getResources().getString(R.string.toast_press_again_exit_app));
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }*/

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventLogin(LoginEvent event) {
        if (event.isLogin()) {
            LogX.i("### 登录成功");
        } else {
            LogX.i("### 退出登录成功");
        }
    }
}
